<template>
  <div>
    <div class="steps">
      <el-steps :active="activeIndex" finish-status="success" simple>
        <el-step title="询报价信息" />
        <el-step title="定标信息" />
      </el-steps>
    </div>
    <el-card class="basic-info">
      <div slot="header">
        <span class="ym-custom ym-custom-bookmark jiBenInfo">定标商品信息</span>
        <div v-if="canEdit()" class="operating-area">
          <div class="urgent-order">
            <el-select
              size="mini"
              clearable
              style="width: 180px; margin-right: 10px"
              v-model="timeoutReason"
              placeholder="批量维护超时原因"
              @change="batchUpdateTimeoutReason"
            >
              <el-option
                v-for="item in INQUERY_TIMEOUT_REASON_OPTION"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-input
              size="mini"
              style="width: 180px"
              v-model.trim="timeoutRemark"
              placeholder="批量维护超时原因备注"
              @input="batchUpdateTimeoutRemark"
              :maxlength="100"
            />
          </div>
          <el-button size="mini" :loading="updateImgLoading" @click="handleUpdateImgInfo">维护图文信息</el-button>
          <el-button size="mini" @click="handleBackQuotePage">重新报价</el-button>
          <el-button size="mini" :loading="plusSizeLoading" @click="plusSizeHandler">商品信息维护</el-button>
          <el-button
            v-if="canEdit()"
            type="primary"
            size="mini"
            :loading="submitLoading"
            @click="handleCompleteInquiry"
          >询价完成</el-button>
        </div>
      </div>
      <div class="table">
        <pl-table
          ref="table"
          use-virtual
          v-loading="tableLoading"
          stripe
          border
          show-summary
          :summary-method="summaryMethod"
          :header-cell-style="{ textAlign: 'center' }"
          :cell-style="{ textAlign: 'center' }"
          :data="dataList"
          :max-height="580"
          :row-height="42"
          size="mini"
        >
          <template v-for="item in columns">
            <el-table-column
              v-if="!item.child.length"
              :key="item.prop"
              fixed
              :prop="item.prop"
              :label="item.label"
              :min-width="item.width || 80"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <span v-if="item.prop == 'timeoutRemark' && canEdit()">
                  <el-input
                    :class="{ active: scope.row.timelyStr == '超时' && !scope.row[scope.column.property] }"
                    v-model.trim="scope.row[scope.column.property]"
                    size="mini"
                    :maxlength="100"
                  />
                </span>
                <span v-else-if="item.prop == 'timeoutReason'">
                  <el-select
                    :class="{ active: scope.row.timelyStr == '超时' && !scope.row[scope.column.property] }"
                    v-model="scope.row[scope.column.property]"
                    placeholder="请选择"
                    size="mini"
                    clearable
                    :disabled="!canEdit()"
                  >
                    <el-option
                      v-for="item in INQUERY_TIMEOUT_REASON_OPTION"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </span>
                <span v-else>
                  <span>{{ scope.row[scope.column.property] }}</span>
                </span>
              </template>
            </el-table-column>
            <el-table-column
              v-else
              :key="item.label"
              :label="item.label"
            >
              <el-table-column
                v-for="child in item.child"
                :key="child.prop"
                :prop="child.prop"
                :property="child.prop"
                :label="child.label"
                :width="child.width"
              >
                <template slot-scope="scope">
                  <span v-if="child.prop.includes('remark') && canEdit()">
                    <el-input
                      v-model="scope.row[scope.column.property]"
                      @input="((val)=>{inputChange(val, scope.row, scope.column.property)})"
                      :disabled="scope.row[scope.column.property] === undefined"
                      size="mini"
                    />
                  </span>
                  <span v-else-if="child.prop.includes('isMarked')">
                    <el-checkbox
                      v-model="scope.row[scope.column.property]"
                      @change="((val)=>{isMarkedCheckChange(val, scope.row, scope.column.property)})"
                      :disabled="!canEdit() || scope.row[scope.column.property] == null"
                    />
                  </span>
                  <span v-else>{{ scope.row[scope.column.property] }}</span>
                </template>
              </el-table-column>
            </el-table-column>
          </template>
        </pl-table>
      </div>
      <div v-if="!canEdit()" class="calibration-detail-info">
        <div class="content">
          <span>定标人：{{calibrationUserInfo.targetUser || ''}}</span>
          <span>定标人公司：{{calibrationUserInfo.targetCompany || ''}}</span>
          <span>定标时间：{{calibrationUserInfo.targetDate || ''}}</span>
        </div>
      </div>
      <el-row v-if="!canEdit()" type="flex" justify="center">
        <el-button type="primary" @click="handleCancel">返回</el-button>
        <el-button type="primary" @click="handleBackQuotePage">上一步</el-button>
      </el-row>
    </el-card>
    <SaleAreaTip
      :visible.sync="tipVisible"
      :skuList="noSaleAreaSkuList"
    />
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import { isResponseSuccess, PRODUCT_TYPE_TEMPORARY_CODE, summaryMethod } from '../../utils'
import { toFixedCustomize, handleOpenNewPage } from '@/utils/bizUtils'
import { INQUERY_TIMEOUT_REASON_OPTION } from '@/pages/sourcing/constants';
import {
  getInqueryCalibrationInfoService,
  updateImgInfoService,
  completeInquiryService, // 询价完成
  updateSkuCodeService // 一物多码商品修改主码
} from '@/api/sourcing/purchaseDetail'
import SaleAreaTip from '@sourcing/components/SaleAreaTip'

export default {
  name: 'CalibrationInfo',
  components: {
    SaleAreaTip
  },
  data () {
    return {
      tipVisible: false,
      noSaleAreaSkuList: [],
      submitLoading: false,
      updateImgLoading: false,
      INQUERY_TIMEOUT_REASON_OPTION,
      timeoutReason: '',
      timeoutRemark: '',
      activeIndex: 1,
      dataList: [],
      calibrationList: [],
      tableLoading: false,
      queryParams: {
        isEdit: '',
        pageType: '',
        sourcingBillId: '',
        isDemand: false,
      },
      columns: [
        {
          label: '商品代码',
          prop: 'skuCode',
          child: [],
        },
        {
          label: '商品名称',
          prop: 'skuName',
          child: [],
        },
        {
          label: '规格型号',
          prop: 'productSpec',
          width: 70,
          child: [],
        },
        {
          label: '单位',
          prop: 'unit',
          width: 50,
          child: [],
        },
        {
          label: '数量',
          prop: 'amount',
          width: 50,
          child: [],
        },
        {
          label: '图文完善状态',
          prop: 'imageStatusStr',
          width: 100,
          child: [],
        },
        {
          label: '询价是否超时',
          prop: 'timelyStr',
          child: [],
        },
        {
          label: '超时原因',
          prop: 'timeoutReason',
          width: 160,
          child: [],
        },
        {
          label: '超时原因备注',
          prop: 'timeoutRemark',
          width: 100,
          child: [],
        },
      ],
      calibrationUserInfo: {}
    };
  },

  computed: {
    ...mapState('sourcing/purchaseDetail', {
      plusSizeLoading: (state) => state.plusSizeLoading, // 商品信息维护loading
    }),
  },

  created () {
    const detailInfo = JSON.parse(sessionStorage.getItem('detailInfo'));
    this.queryParams = { ...detailInfo };
    this.getTableData()
  },
  methods: {
    summaryMethod,
    ...mapActions('sourcing/purchaseDetail', [
      'completeInquiry', // 询价完成
      'getOrderNo', // 商品中心临采商品单据标识
    ]),
    // 获取定标信息
    async getTableData () {
      const { sourcingBillId } = this.queryParams;
      const data = {
        isCompleteWinBill: sessionStorage.getItem('isCompleteWinBill'),
        sourcingBillId,
      }
      const res = await getInqueryCalibrationInfoService(data, state => { this.tableLoading = state })
      if (res) {
        const { skuList, targetCompany, targetDate, targetUser } = res.data.winBiddingDto
        this.calibrationList = skuList
        this.calibrationUserInfo = {
          targetCompany,
          targetDate,
          targetUser
        }
        this.formatSourceDataAndTitle(skuList)
      }
    },
    // 展示无销售区域商品列表
    showNoSaleAreaTip (skuList) {
      this.tipVisible = true;
      this.noSaleAreaSkuList = skuList;
    },
    // 维护图文信息
    async handleUpdateImgInfo () {
      const { sourcingBillId } = this.queryParams
      const res = await updateImgInfoService({ sourcingBillId }, state => { this.updateImgLoading = state })
      if (res) {
        const { data } = res;
        localStorage.setItem('sourcing_bid_skus', JSON.stringify(data))
        handleOpenNewPage(this, { name: 'calibratePerfectGraphics' })
      }
    },
    // 线索商品为一物多码商品
    async handleUpdateSkuCode () {
      const { sourcingBillId } = this.queryParams
      const res = await updateSkuCodeService({ sourcingBillId }, state => { this.tableLoading = state })
      if (res) {
        const { data } = res;
        if (data) {
          this.handleBackQuotePage()
        }
      }
    },
    // 批量修改超时原因
    batchUpdateTimeoutReason (val) {
      this.dataList = this.dataList.map(item => ({
        ...item,
        timeoutReason: val
      }))
    },
    // 批量修改超时原因
    batchUpdateTimeoutRemark (val) {
      this.dataList = this.dataList.map(item => ({
        ...item,
        timeoutRemark: val
      }))
    },
    // 格式化表头
    formatSourceDataAndTitle (skuList) {
      skuList.forEach((item) => {
        item.supplierList && item.supplierList.forEach((ele, index) => {
          if (ele.recommendNum) {
            ele.isMarked = true;
          } else {
            ele.isMarked = false;
          }
          Object.keys(ele).forEach((key) => {
            item[key + '_' + ele.supplierId] = ele[key]
          })
          let obj = {
            label: ele.supplierName,
            prop: '',
            child: [
              {
                label: '归属中心',
                prop: `belongDepartmentName_${ele.supplierId}`,
              },
              {
                label: '成本价',
                prop: `costPrice_${ele.supplierId}`,
              },
              {
                label: '中标数量',
                prop: `recommendNum_${ele.supplierId}`,
              },
              {
                label: '中标金额',
                prop: `skuPrice_${ele.supplierId}`,
              },
              {
                label: '报价金额',
                prop: `totalPrice_${ele.supplierId}`,
              },
              {
                label: '交货期',
                prop: `deliveryDate_${ele.supplierId}`,
              },
              {
                label: '备注',
                prop: `remark_${ele.supplierId}`,
                width: 100
              },
              {
                label: '中标',
                prop: `isMarked_${ele.supplierId}`,
                width: 50,
              }
            ]
          };
          if (this.columns.every(item => (item.label !== obj.label))) {
            this.columns.push(obj)
          }
        })
        this.dataList.push(item);
      })
    },
    inputChange (val, row, prop) {
      if (!prop.includes('remark')) {
        this.dataList.forEach(item => {
          if (item.sourcingBillDetailsId === row.sourcingBillDetailsId) {
            let tag = prop.split('_')[1];
            item[`skuPrice_${tag}`] = toFixedCustomize(item[`costPrice_${tag}`] * (val))
          }
        })
      }
      this.$forceUpdate()
    },
    isMarkedCheckChange (val, row, prop) {
      this.dataList.forEach(item => {
        if (item.sourcingBillDetailsId === row.sourcingBillDetailsId) {
          let tag = prop.split('_')[1];
          if (val) {
            Object.keys(item).forEach(key => {
              if (key.includes('recommendNum') && key.split('_')[1] === tag) {
                item[`recommendNum_${tag}`] = item.amount;
                item[`skuPrice_${tag}`] = toFixedCustomize(item[`costPrice_${tag}`] * item[`recommendNum_${tag}`]);
              } else if (key.includes('recommendNum') && key.split('_')[1] !== tag) {
                item[`recommendNum_${key.split('_')[1]}`] = 0;
                item[`isMarked_${key.split('_')[1]}`] = false;
              }
            })
          } else {
            item[`recommendNum_${tag}`] = 0;
          }
        }
      })
      this.$forceUpdate()
    },
    // 询价完成
    handleCompleteInquiry () {
      let inquirySubmitData = {
        sourceBillId: this.queryParams.sourcingBillId || '',
        winbidReqDtoList: []
      }
      let data = this.dataList.map(item => ({ ...item }))
      data.forEach(item => {
        let obj = {
          skuCode: item.skuCode,
          timelyStr: item.timelyStr,
          timeoutReason: item.timeoutReason,
          timeoutRemark: item.timeoutRemark,
          sourceSupplierId: '',
          remark: '',
        }
        Object.keys(item).forEach(key => {
          if (key.includes('isMarked') && item[key]) {
            let tag = key.split('_')[1]
            obj.sourceSupplierId = item[`sourcingSupplierId_${tag}`]
            obj.remark = item[`remark_${tag}`];
            inquirySubmitData.winbidReqDtoList.push(obj)
          }
        })
      })
      if (inquirySubmitData.winbidReqDtoList.length !== this.calibrationList.length) {
        return this.$message.warning('中标商品数量与需求数量不一致')
      }
      if (inquirySubmitData.winbidReqDtoList.some(item => item.timelyStr == '超时' && (!item.timeoutReason || !item.timeoutRemark))) {
        return this.$message.warning(`询价超时的商品，超时原因及备注不能为空`);
      }
      console.log(inquirySubmitData)
      this.handleSubmit(inquirySubmitData);
    },
    // 询价完成提交
    async handleSubmit (data) {
      const res = await completeInquiryService(data, state => { this.submitLoading = state })
      if (res) {
        if (res.data) {
          // checkType 201 线索商品为一物多码商品 202 需维护图文 204 存在无销售区域商品
          const { checkType, data, msg } = res.data;
          if (checkType == 204) {
            this.showNoSaleAreaTip(data)
          } else {
            this.$confirm(`${msg}`, '提示', {
              type: 'warning',
            }).then(() => {
              if (checkType == 201) {
                this.handleUpdateSkuCode()
              }
              if (checkType == 202) {
                this.handleUpdateImgInfo()
              }
            }).catch(() => {})
          }
        } else {
          this.$message.success(res.msg);
          this.backToInquery()
        }
      }
    },
    // 商品加码 - 商品信息维护
    plusSizeHandler () {
      if (this.hasTemporaryGoods()) {
        const cb = (res) => {
          if (isResponseSuccess(res)) {
            this.$message.success(res.msg);
            this.$router.push({ name: 'temporaryAddCode', query: { type: 2, sourceBillId: res.data } })
          }
        };
        const data = {
          sourceBillId: this.queryParams.sourcingBillId,
        };
        this.getOrderNo({
          payload: {
            data,
            cb,
          },
        });
      } else {
        this.$message.warning('无线索商品，无需维护.')
      }
    },
    hasTemporaryGoods () {
      return this.calibrationList.some(item => (item.skuType == PRODUCT_TYPE_TEMPORARY_CODE))
    },
    // 存在未加码临采商品
    hasUncodedTemporaryGoods () {
      return this.calibrationList.some(item => (!item.skuCode))
    },
    // 是否可编辑
    canEdit () {
      return this.queryParams.isEdit === true;
    },
    // 是否为需求管理
    isDemand () {
      return this.queryParams.isDemand;
    },
    // 返回询价首页
    backToInquery () {
      if (this.isDemand()) {
        this.$router.push({ name: 'demandInquiry', query: { sts: '10' } }); // 询价完成跳转待受理
      } else {
        this.$router.push({ name: 'demandInquiry', query: { sts: '10' } }); // 定标完成跳转待生成订单
      }
    },
    // 重新报价
    handleBackQuotePage () {
      if (this.isDemand()) {
        this.$router.push({ name: 'demandPurchaseDetail' });
      } else {
        this.$router.push({ name: 'purchaseDetail' });
      }
    },
    // 返回
    handleCancel () {
      if (this.isDemand()) {
        this.$router.push({ name: 'demandInquiry' });
      } else {
        this.$router.push({ name: 'inquiry' });
      }
    },
  },
};
</script>

<style lang="less" scoped>
.operate-area {
  margin: 15px;
}
.basic-info {
  margin: 10px 0;
  .operating-area {
    float: right;
    .urgent-order {
      display: inline;
      margin-right: 10px;
    }
  }
}
.calibration-detail-info {
  margin: 10px 0;
  .content {
    margin-top: 10px;
    span {
      margin-right: 30px;
      color: #909399;
      font-size: 12px;
    }
  }
}
/deep/ .has-gutter {
  tr td .cell {
    text-align: center;
  }
}
.active {
  border: 1px dashed red;
  border-radius: 4px;
  /deep/ input {
    border: none;
  }
}
/deep/ .el-table--scrollable-x .el-table__body-wrapper {
  overflow-x: auto;
  z-index: 1;
}
</style>
